package com.afdor.rws.dtm.transaction;

import java.sql.Connection;
import java.util.Arrays;
import java.util.Objects;

/**
 * 二阶段分布式事务中本地事务的事务隔离级别
 *
 * @author 悭梵
 * @date Created in 2018-10-12 11:45
 * @see org.springframework.transaction.TransactionDefinition
 */
public enum Isolation {
    /**
     * @see org.springframework.transaction.TransactionDefinition.ISOLATION_DEFAULT
     * @see org.springframework.transaction.annotation.Isolation.DEFAULT
     */
    DEFAULT(-1),
    /**
     * @see org.springframework.transaction.TransactionDefinition.ISOLATION_READ_UNCOMMITTED
     * @see org.springframework.transaction.annotation.Isolation.READ_UNCOMMITTED
     */
    READ_UNCOMMITTED(Connection.TRANSACTION_READ_UNCOMMITTED),
    /**
     * @see org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED
     * @see org.springframework.transaction.annotation.Isolation.READ_COMMITTED
     */
    READ_COMMITTED(Connection.TRANSACTION_READ_COMMITTED),
    /**
     * @see org.springframework.transaction.TransactionDefinition.ISOLATION_REPEATABLE_READ
     * @see org.springframework.transaction.annotation.Isolation.REPEATABLE_READ
     */
    REPEATABLE_READ(Connection.TRANSACTION_REPEATABLE_READ),
    /**
     * @see org.springframework.transaction.TransactionDefinition.ISOLATION_SERIALIZABLE
     * @see org.springframework.transaction.annotation.Isolation.SERIALIZABLE
     */
    SERIALIZABLE(Connection.TRANSACTION_SERIALIZABLE);

    private final int value;

    Isolation(int value) {
        this.value = value;
    }

    public int value() {
        return this.value;
    }

    public static Isolation acquireByValue(final int value) {
        return Arrays.stream(Isolation.values())
                .filter(v -> Objects.equals(v.value(), value))
                .findFirst()
                .orElse(Isolation.DEFAULT);
    }
}
